package com.hyk.interceptor;

import com.hyk.entity.Menu;
import com.hyk.entity.User;
import com.hyk.enums.ApiEnum;
import com.hyk.exception.GlobalException;
import com.hyk.service.IMenuService;
import com.hyk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    private static final String noTokenPath = "/user/login,/user/add,/doc.html";

    private static final String NOPRESS = "/user/login,/user/add,/doc.html,/user/verificationCode";

    @Autowired
    private RedisTemplate<String ,Object> redisTemplate;

    @Autowired
    private IMenuService menuService;

    public JwtInterceptor(){}

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //如果不是post请求，直接放行
        String method = request.getMethod();
        if (!"POST".equalsIgnoreCase(method))
            return true;

        String servletPath = request.getServletPath();
        for (String str:noTokenPath.split(",")){
            if (str.equals(servletPath)){
                return true;
            }
        }

        String authorization = request.getHeader("Authorization");
        if (StringUtils.isBlank(authorization)){
            throw new GlobalException(ApiEnum.TOKEN_IS_ILLEGAL);
        }

        Claims claims = JwtUtils.parseJWT(authorization);
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        String role = claims.get("role", String.class);
        User user = (User) redisTemplate.opsForValue().get(userId+"_user_login_token");
        request.setAttribute("user-token",user);
        //todo redis

        List<Menu> menus = menuService.findMenuByRole(role);
        for(String str : NOPRESS.split(",")){
            for(Menu menu : menus){
                if(menu.getPath() == str){
                    return true;
                }
            }
        }
        for(Menu menu : menus){
            if(!menu.equals(servletPath)){
                throw new GlobalException(ApiEnum.USER_NOT_PRESS);
            }
        }

        return true;
    }
}
